﻿using System;
using System.Collections.Generic;

using System.Text;

using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.Expando;
using System.Net;
using System.Drawing;
using System.IO;

using SHDocVw;


using Microsoft.Win32;
namespace aslive.imgPasterUpload.ie.BHO
{
    [ComVisible(true),
    ClassInterface(ClassInterfaceType.None),
    Guid("DA8EA345-02AE-434E-82E9-448E3DB7629E"),
    ProgId("asLiveImgPasterUpload"),
    ComDefaultInterface(typeof(IExtension))]

    public class BHO:IObjectWithSite,IExtension
    {
        SHDocVw.WebBrowser webBroswer;


        Boolean _Lock=false;
        DateTime _uploadStartUsingTime;
        int _progress;
        string _fileUrl;
        
        public void onDocumentComplete(object pDisp,ref object URL){


                dynamic window = webBroswer.Document.parentWindow;

                IExpando windowEx = (IExpando)window;
                windowEx.AddProperty("asLiveImgPaster");
                window.asLiveImgPaster = this;



        }
        int IObjectWithSite.SetSite(object site)
        {
            if (site != null)
            {
                webBroswer = (SHDocVw.WebBrowser)site;
                webBroswer.DocumentComplete += new DWebBrowserEvents2_DocumentCompleteEventHandler(this.onDocumentComplete);
            }
            else {
                webBroswer.DocumentComplete -= new DWebBrowserEvents2_DocumentCompleteEventHandler(this.onDocumentComplete);    
            }
            return 0;
        }

        int IObjectWithSite.GetSite(ref Guid guid, out IntPtr ppvSite)
        {
            IntPtr punk = Marshal.GetIUnknownForObject(webBroswer);
            int hr = Marshal.QueryInterface(punk,ref guid,out ppvSite);
            Marshal.Release(punk);
            return hr;
        }


        public Boolean paster(string postUrl, string compeleteFun = null, string progressFun = null)
        {

            if (_Lock) {
                MessageBox.Show("有文件正在上传.....");
                return false;
            }
            try
            {
                if (Clipboard.ContainsImage())
                {
                    Image img = Clipboard.GetImage();
                    var extName="";
                    var fileName="";
                    if (Clipboard.GetFileDropList().Count > 0 )
                    { 
                        extName= Path.GetExtension(Clipboard.GetFileDropList()[0]).ToLower();
                        //gif图形文件剪切
                        if (extName == ".gif" || extName == ".png" || extName==".jpg")
                        {
                            fileName=Clipboard.GetFileDropList()[0];

                            
                            //MessageBox.Show("GIF && PNG");
                        }

                    }
                    else
                    {
                        img.Save("windbell2_temPasterImg.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                        fileName = "windbell2_temPasterImg.jpg";


                        //MessageBox.Show("生成JPG");
                    }
                    WebClient wc = new WebClient();
                    wc.UploadProgressChanged += new UploadProgressChangedEventHandler(uploadProgressHandle);
                    
                    wc.UploadFileCompleted += new UploadFileCompletedEventHandler((object o, UploadFileCompletedEventArgs e) => {
                        _Lock = false;
                        _fileUrl = System.Text.Encoding.Default.GetString(e.Result);
                        //MessageBox.Show(_fileUrl);

                    });

                    //开始上传
                    _uploadStartUsingTime = DateTime.Now;
                    _Lock = true;
                    _progress = 0;

                    wc.UploadFileAsync(new Uri(postUrl), "POST", fileName);
                    if (extName != "")
                    {
                        File.Delete("windbell2_temPasterImg.jpg");
                    }
                    return true;

                }
                else {
                    MessageBox.Show("得不到所需的图片格式");
                    return false;
                }
            }
            catch( Exception e) {
                MessageBox.Show("解析剪切板异常:"+e.Message);
                return false;
            }

        }
        private void uploadProgressHandle(object o,UploadProgressChangedEventArgs e) {


            this._progress = e.ProgressPercentage;
                //doc.parentWindow.execScript(javascript_progressFun + "('"+e.ProgressPercentage+"');", "JavaScript");

        }

        public static string BHOKEYNAME = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Browser Helper Objects";
        [ComRegisterFunction]
        public static void RegisterBHO(Type type) {
            RegistryKey rk = Registry.LocalMachine.OpenSubKey(BHOKEYNAME, true);
            if (rk == null) {
                rk = Registry.LocalMachine.CreateSubKey(BHOKEYNAME);
            }
            string guid = type.GUID.ToString("B");
            RegistryKey ok = rk.OpenSubKey(guid);

            if (ok == null)
            {
                ok = rk.CreateSubKey(guid);
            }
            ok.SetValue("Alright",1);
            rk.Close();
            ok.Close();


        }
        [ComUnregisterFunction]
        public static void UnregisterBHO(Type type)
        {
            RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(BHOKEYNAME, true);
            string guid = type.GUID.ToString("B");

            if (registryKey != null)
                registryKey.DeleteSubKey(guid, false);
        }
 

        public int progress
        {
            get { return this._progress; }
        }
    

        public string fileUrl
        {
            get { return this._fileUrl; }
        }

        public bool Lock
        {
            get { return this._Lock; }
        }
        public int uploadUsingTime
        {
            get { return (this._uploadStartUsingTime - DateTime.Now).Seconds; }
        }
        public string info
        {
            set { info = value; }
            get{return "开发by asLive.windbell2";}
        }       
    }

}
